# -*- coding: utf-8 -*-
"""
用户云存储账号模型
@api-version: 1.0.0
"""

from datetime import datetime
from . import db
import json

class CloudStorageAccount(db.Model):
    """用户云存储账号模型"""
    __tablename__ = 'user_cloud_storage_accounts'
    
    id = db.Column(db.Integer, primary_key=True, comment='主键ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, comment='用户ID（可为空，表示公共账号）')
    cloud_provider = db.Column(db.String(50), nullable=False, comment='云存储提供商 1 天翼云盘(暂时支持天翼云盘)')
    cloud_account = db.Column(db.String(100), nullable=False, comment='云存储账号')
    cloud_password = db.Column(db.String(100), nullable=False, comment='云存储密码')
    cloud_token = db.Column(db.String(500), nullable=False, comment='云存储Token')
    cloud_token_info = db.Column(db.String(3000), nullable=False, comment='Json格式的Token信息')
    root_directory_id = db.Column(db.String(255), nullable=False, comment='根目录ID')
    storage_quota = db.Column(db.BigInteger, nullable=False, comment='存储配额（字节，默认10GB）')
    is_active = db.Column(db.Boolean, nullable=False, default=True, comment='账号状态（0-禁用，1-启用）')
    is_online = db.Column(db.Boolean, nullable=False, default=False, comment='在线状态（0-离线，1-在线）')
    last_check_at = db.Column(db.DateTime, nullable=True, comment='最后检测时间')
    cloud_expires_at = db.Column(db.DateTime, nullable=False, comment='云存储过期时间')
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, 
                          onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    user = db.relationship('User', backref=db.backref('cloud_accounts', lazy='dynamic'))
    
    def __init__(self, cloud_provider, cloud_account, cloud_password, 
                 cloud_token, cloud_token_info, root_directory_id, storage_quota=10*1024*1024*1024,
                 is_active=True, cloud_expires_at=None, user_id=None):
        self.user_id = user_id
        self.cloud_provider = cloud_provider
        self.cloud_account = cloud_account
        self.cloud_password = cloud_password
        self.cloud_token = cloud_token
        self.cloud_token_info = cloud_token_info
        self.root_directory_id = root_directory_id
        self.storage_quota = storage_quota  # 默认10GB
        self.is_active = is_active
        self.is_online = False  # 默认离线
        self.last_check_at = None
        self.cloud_expires_at = cloud_expires_at or datetime.utcnow()
    
    def get_token_info(self):
        """获取Token信息的JSON对象"""
        try:
            return json.loads(self.cloud_token_info)
        except:
            return {}
    
    def set_token_info(self, token_info):
        """设置Token信息"""
        if isinstance(token_info, dict):
            self.cloud_token_info = json.dumps(token_info)
        else:
            self.cloud_token_info = str(token_info)
    
    def is_expired(self):
        """检查Token是否过期"""
        return datetime.utcnow() > self.cloud_expires_at
    
    def update_online_status(self, is_online):
        """更新在线状态"""
        self.is_online = is_online
        self.last_check_at = datetime.utcnow()
    
    def get_status_display(self):
        """获取状态显示文本"""
        if not self.is_active:
            return '已禁用'
        elif self.is_expired():
            return '已过期'
        elif self.is_online:
            return '在线'
        else:
            return '离线'
    
    def to_dict(self, include_sensitive=False):
        """转换为字典"""
        data = {
            'id': self.id,
            'userId': self.user_id,
            'cloudProvider': self.cloud_provider,
            'cloudAccount': self.cloud_account,
            'rootDirectoryId': self.root_directory_id,
            'storageQuota': self.storage_quota,
            'isActive': self.is_active,
            'isOnline': self.is_online,
            'lastCheckAt': self.last_check_at.isoformat() if self.last_check_at else None,
            'statusDisplay': self.get_status_display(),
            'cloudExpiresAt': self.cloud_expires_at.isoformat() if self.cloud_expires_at else None,
            'createdAt': self.created_at.isoformat() if self.created_at else None,
            'updatedAt': self.updated_at.isoformat() if self.updated_at else None
        }
        
        if include_sensitive:
            data['cloudPassword'] = self.cloud_password
            data['cloudToken'] = self.cloud_token
            data['cloudTokenInfo'] = self.get_token_info()
        
        return data